package com.jsh.mypor.controller;

import com.atguigu.zhxy.util.CreateVerifiCodeImage;
import com.jsh.mypor.pojo.Admin;
import com.jsh.mypor.pojo.LoginForm;
import com.jsh.mypor.pojo.Student;
import com.jsh.mypor.pojo.Teacher;
import com.jsh.mypor.service.AdminService;
import com.jsh.mypor.service.StudentService;
import com.jsh.mypor.service.TeacherService;
import com.jsh.mypor.util.JwtHelper;
import com.jsh.mypor.util.Result;
import com.jsh.mypor.util.ResultCodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/sms/system")
public class SystemController {
    @Autowired
    private  TeacherService teacherService;
    @Autowired
    private StudentService studentService;
    @Autowired
    private AdminService adminService;

   //POST headerImgUpload
    @PostMapping("/headerImgUpload")
    public  Result headerImgUpload(
            @RequestPart("multipartFile")MultipartFile multipartFile,
            HttpServletRequest request
            ){
        String uuid= UUID.randomUUID().toString().replace("-","").toLowerCase(Locale.ROOT);
        String originalFilename = multipartFile.getOriginalFilename();
        int i = originalFilename.lastIndexOf(".");
        String newFileName=uuid+originalFilename.substring(i);
        String portraitPath="D:/IdeaProject/MyPor/target/classes/public/upload/".concat(newFileName);
        try {
            multipartFile.transferTo(new File(portraitPath));
        } catch (IOException e) {
            e.printStackTrace();
        }
        String path="upload/".concat(newFileName);
        return Result.ok(path);
    }
    @GetMapping("/getInfo")
    public Result getInfoByToken(@RequestHeader("token") String token){

        boolean expiration = JwtHelper.isExpiration(token);
        if (expiration){
            return Result.build(null, ResultCodeEnum.SUCCESS.TOKEN_ERROR);
        }
        Long userId = JwtHelper.getUserId(token);
        Integer userType = JwtHelper.getUserType(token);
        Map<String,Object> map=new HashMap<>();
        switch (userType){
            case 1:
                Admin admin=adminService.getAdminById(userId);
                map.put("userType",1);
                map.put("user",admin);
                break;
            case 2:
                Student student=studentService.getStudentById(userId);
                map.put("userType",2);
                map.put("user",student);
                break;
            case 3:
                Teacher teacher=teacherService.getTeacherById(userId);
                map.put("userType",3);
                map.put("user",teacher);
                break;

        }
        return Result.ok(map);

    }
    @PostMapping("/login")
    public Result login(@RequestBody LoginForm loginForm, HttpServletRequest request){


        //验证码校验
        String sessionVerifiCode = (String) request.getSession().getAttribute("verifiCode");
        String loginVerifiCode=loginForm.getVerifiCode();
        if ("".equals(sessionVerifiCode)||null==sessionVerifiCode){
            return Result.fail().message("验证码失效，请稍后在试");
        }
        if (!sessionVerifiCode.equalsIgnoreCase(loginVerifiCode)){
            return Result.fail().message("验证码错误，请重新输入");
        }
        //从session中移除验证码
        request.removeAttribute("verifiCode");
        //分用户类型进行校验
        Map<String,Object> map=new HashMap<>();
        switch (loginForm.getUserType()){
            case 1:
                Admin admin=adminService.login(loginForm);
                try {
                    if(admin!=null){
                        map.put("token", JwtHelper.createToken(admin.getId().longValue(),1));
                    }else {
                        throw new RuntimeException("用户或者密码错误");
                    }
                    return Result.ok(map);
                } catch (RuntimeException e) {
                    e.printStackTrace();
                    return Result.fail().message(e.getMessage());
                }
            case 2:
                Student student=studentService.login(loginForm);
                try {
                    if(student!=null){
                        map.put("token", JwtHelper.createToken(student.getId().longValue(),2));
                    }else {
                        throw new RuntimeException("用户或者密码错误");
                    }
                    return Result.ok(map);
                } catch (RuntimeException e) {
                    e.printStackTrace();
                    return Result.fail().message(e.getMessage());
                }
            case 3:
                Teacher teacher=teacherService.login(loginForm);
                try {
                    if(teacher!=null){
                        map.put("token", JwtHelper.createToken(teacher.getId().longValue(),3));
                    }else {
                        throw new RuntimeException("用户或者密码错误");
                    }
                    return Result.ok(map);
                } catch (RuntimeException e) {
                    e.printStackTrace();
                    return Result.fail().message(e.getMessage());
                }

        }
        return Result.ok();
    }
    @GetMapping("/getVerifiCodeImage")
    public void getVerifiCodeImage(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //获取图片
        BufferedImage verifiCodeImage = CreateVerifiCodeImage.getVerifiCodeImage();
        //获取图片上的验证码
        String verifiCode = new String(CreateVerifiCodeImage.getVerifiCode());
        //将验证码文本放到session中，为下次验证做准备
        HttpSession session = request.getSession();
        session.setAttribute("verifiCode",verifiCode);
        //将验证码图片响应给游览器

        ImageIO.write(verifiCodeImage,"JPEG",response.getOutputStream());
    }
}
